package com.huawei.java.datahandle;

import com.huawei.java.model.TimestampResult;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.TreeSet;

public class ResultWriter {
    public static void writeResult(TreeSet<TimestampResult> timestampResults) {
        for (TimestampResult timestampResult : timestampResults) {
            Map<String, Map<String, Integer>> allocationMaps = timestampResult.getAllocationMaps();
            try (BufferedWriter bWriter = new BufferedWriter(new FileWriter(FileConstant.RESULT_FILE_PATH, true))){
                for (Map.Entry<String, Map<String, Integer>> entry : allocationMaps.entrySet()) {
                    StringBuilder clientAllocationInfo = new StringBuilder();
                    clientAllocationInfo.append(entry.getKey()).append(FileConstant.COLON);
                    for (Map.Entry<String, Integer> integerEntry : entry.getValue().entrySet()) {
                        clientAllocationInfo.append(FileConstant.LEFT_BRACKET)
                                .append(integerEntry.getKey())
                                .append(FileConstant.COMMA)
                                .append(integerEntry.getValue())
                                .append(FileConstant.RIGHT_BRACKET)
                                .append(FileConstant.COMMA);
                    }
                    clientAllocationInfo.delete(clientAllocationInfo.length() - 1, clientAllocationInfo.length());
                    bWriter.write(clientAllocationInfo.append(System.lineSeparator()).toString());
                    clientAllocationInfo.setLength(0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteResultFile() {
        File file = new File(FileConstant.RESULT_FILE_PATH);
        if (file.exists()) {
            file.delete();
        }
    }
}
